package com.ysz.learn.selflearn.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.ysz.learn.selflearn.annotation.MyLog;

/**
 * 切面类
 *
 * @author: yushizhong
 * @date: 2021-10-28 15:18
 * @version: 1.0
 **/
@Aspect
@Component
public class MyLogAspect {
    @Pointcut("@annotation(com.ysz.learn.selflearn.annotation.MyLog)")
    public void logPointCut() {

    };

    @Before("logPointCut()")
    public void logAround(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] param = joinPoint.getArgs();

        StringBuilder sb = new StringBuilder();

        for (Object o : param) {
            sb.append(o + "; ");

        }
        System.out.println("进入[" + methodName + "]方法,参数为:" + sb.toString());

        System.out.println(methodName + "方法执行结束");

    }

    @AfterReturning("logPointCut()")
    public void aa(JoinPoint joinPoint) {
        String targetName = joinPoint.getTarget().getClass().getName(); // 获得执行方法的类名
        String methodName = joinPoint.getSignature().getName(); // 获得执行方法的方法名
        Object[] arguments = joinPoint.getArgs(); // 获取切点方法的所有参数类型
        try {
            Class targetClass = Class.forName(targetName);

            Method[] methods = targetClass.getMethods(); // 获取公共方法，不包括类私有的
            String value = "";
            String name = "";
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] clazzs = method.getParameterTypes(); // 对比方法中参数的个数
                    if (clazzs.length == arguments.length) {
                        value = method.getAnnotation(MyLog.class).value();
                        name = method.getAnnotation(MyLog.class).name();
                        break;
                    }
                }
            }
            System.out.println("value=" + value);
            System.out.println("name=" + name);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
